// XXL-JOB 文档优化脚本
(function() {
  'use strict';

  let isEnabled = false; // 插件启用状态
  let tocContainer = null;

  // 等待页面完全加载
  function initOptimization() {
    
    // 先添加控制按钮（不依赖 storage）
    addControlButton();
    
    // 尝试读取保存的状态
    try {
      if (typeof chrome !== 'undefined' && chrome.storage && chrome.storage.sync) {
        chrome.storage.sync.get(['enabled'], function(result) {
          isEnabled = result.enabled === true; // 默认关闭，需要用户手动开启
          
          if (isEnabled) {
            // 确保 DOM 完全加载后再激活
            if (document.readyState === 'loading') {
              document.addEventListener('DOMContentLoaded', function() {
                activatePlugin();
              });
            } else {
              activatePlugin();
            }
          }
          
          updateControlButton();
        });
      } else {
        // 如果 storage API 不可用，默认关闭
        isEnabled = false;
        updateControlButton();
      }
    } catch (e) {
      // 降级方案：默认关闭
      isEnabled = false;
      updateControlButton();
    }
  }

  // 激活插件（带重试机制）
  function activatePlugin() {
    if (tocContainer) return; // 已经激活

    // 尝试查找目录，如果找不到就轮询重试
    tryFindToc(0);
  }

  // 轮询查找目录（最多尝试 10 次，每次间隔 200ms）
  function tryFindToc(attempt) {
    const maxAttempts = 10;
    
    
    // 查找 XXL 系列文档的目录结构
    let tocMenu = document.querySelector('.editormd-toc-menu');
    let markdownToc = null;
    
    if (tocMenu) {
      markdownToc = tocMenu.querySelector('.markdown-toc');
    } else {
      markdownToc = document.querySelector('.markdown-toc');
    }
    
    if (markdownToc) {
      // 找到了，创建目录
      optimizeXXLJobLayout(markdownToc);
      isEnabled = true;
    } else {
      // 没找到
      if (attempt < maxAttempts - 1) {
        // 继续重试
        setTimeout(() => {
          tryFindToc(attempt + 1);
        }, 1000);
      } else {
        // 达到最大重试次数
        isEnabled = true; // 仍然设置为启用状态，按钮保持一致
      }
    }
  }

  // 停用插件
  function deactivatePlugin() {
    if (tocContainer) {
      tocContainer.remove();
      tocContainer = null;
    }

    // 移除 body 的类
    document.body.classList.remove('xxljob-optimized');
    
    // 恢复原始目录显示
    const originalToc = document.querySelector('.markdown-toc');
    if (originalToc) {
      originalToc.style.display = '';
    }

    isEnabled = false;
  }

  // 切换插件状态
  function togglePlugin() {
    
    if (isEnabled) {
      deactivatePlugin();
    } else {
      activatePlugin();
    }

    // 保存状态
    try {
      if (typeof chrome !== 'undefined' && chrome.storage && chrome.storage.sync) {
        chrome.storage.sync.set({ enabled: isEnabled });
      } else {
      }
    } catch (e) {
    }
    
    // 更新按钮文本
    updateControlButton();
  }

  function optimizeXXLJobLayout(markdownToc) {

    // 创建左侧目录容器
    tocContainer = document.createElement('div');
    tocContainer.className = 'xxljob-toc-container';
    tocContainer.id = 'xxljob-toc';

    // 添加目录标题
    const tocTitle = document.createElement('div');
    tocTitle.className = 'toc-title';
    tocTitle.textContent = '📖 目录导航';

    // 克隆目录列表
    const tocList = markdownToc.querySelector('.markdown-toc-list');
    
    if (tocList) {
      const clonedList = tocList.cloneNode(true);
      clonedList.className = 'xxljob-toc-list';
      
      // 删除包含 <h1>目录</h1> 的 li 元素（原网站的目录标题）
      const firstLi = clonedList.querySelector('li > h1');
      if (firstLi && firstLi.parentElement) {
        firstLi.parentElement.remove();
      }
      
      // 处理所有链接 - 不需要阻止默认行为，让它自然跳转
      const links = clonedList.querySelectorAll('a');
      links.forEach(link => {
        link.addEventListener('click', (e) => {
          // 高亮当前项
          links.forEach(a => a.classList.remove('active'));
          link.classList.add('active');
        });
      });

      tocContainer.appendChild(tocTitle);
      tocContainer.appendChild(clonedList);
      
    }

    // 插入目录到页面开头
    document.body.insertBefore(tocContainer, document.body.firstChild);

    // 给 body 添加类，通过 CSS 调整布局
    document.body.classList.add('xxljob-optimized');

    // 添加滚动监听
    addScrollHighlight();
  }

  function createTocFromSidebar(sidebar) {
    // 隐藏原始侧边栏
    sidebar.style.display = 'none';

    // 创建左侧目录容器
    tocContainer = document.createElement('div');
    tocContainer.className = 'xxljob-toc-container';
    tocContainer.id = 'xxljob-toc';

    tocContainer.appendChild(sidebar.cloneNode(true));

    // 插入目录
    document.body.insertBefore(tocContainer, document.body.firstChild);
    document.body.classList.add('xxljob-optimized');
  }

  function createCustomTOC() {
    // 查找所有标题
    const headings = document.querySelectorAll('h1, h2, h3, h4, h5, h6');
    
    if (headings.length === 0) return;

    // 创建目录
    tocContainer = document.createElement('div');
    tocContainer.className = 'xxljob-toc-container custom-toc';
    tocContainer.id = 'xxljob-toc';

    const tocTitle = document.createElement('div');
    tocTitle.className = 'toc-title';
    tocTitle.textContent = '📖 目录';

    const tocList = document.createElement('ul');
    tocList.className = 'toc-list';

    headings.forEach((heading, index) => {
      // 为标题添加ID
      if (!heading.id) {
        heading.id = `heading-${index}`;
      }

      const level = parseInt(heading.tagName.substring(1));
      const listItem = document.createElement('li');
      listItem.className = `toc-level-${level}`;

      const link = document.createElement('a');
      link.href = `#${heading.id}`;
      link.textContent = heading.textContent;
      link.addEventListener('click', () => {
        // 高亮当前项
        document.querySelectorAll('.toc-list a').forEach(a => a.classList.remove('active'));
        link.classList.add('active');
      });

      listItem.appendChild(link);
      tocList.appendChild(listItem);
    });

    tocContainer.appendChild(tocTitle);
    tocContainer.appendChild(tocList);

    // 插入目录
    document.body.insertBefore(tocContainer, document.body.firstChild);
    document.body.classList.add('xxljob-optimized');

    // 添加滚动监听
    addScrollHighlight();
  }

  function addScrollHighlight() {
    let ticking = false;
    
    window.addEventListener('scroll', () => {
      if (!ticking) {
        window.requestAnimationFrame(() => {
          const links = document.querySelectorAll('.xxljob-toc-list a, .toc-list a');
          let currentActive = null;
          
          links.forEach(link => {
            const href = link.getAttribute('href');
            if (href && href.startsWith('#')) {
              const targetId = href.substring(1);
              const targetElement = document.getElementById(targetId) || 
                                   document.querySelector(`[name="${targetId}"]`);
              
              if (targetElement) {
                const rect = targetElement.getBoundingClientRect();
                if (rect.top <= 150 && rect.top >= -100) {
                  currentActive = link;
                }
              }
            }
          });
          
          if (currentActive) {
            links.forEach(a => a.classList.remove('active'));
            currentActive.classList.add('active');
          }
          
          ticking = false;
        });
        ticking = true;
      }
    });
  }

  // 添加控制按钮（启用/禁用插件）
  function addControlButton() {
    
    // 检查是否已存在
    if (document.getElementById('xxljob-control-btn')) {
      return;
    }
    
    const controlBtn = document.createElement('button');
    controlBtn.className = 'xxljob-control-btn';
    controlBtn.id = 'xxljob-control-btn';
    controlBtn.innerHTML = '📖';
    controlBtn.title = '点击切换目录优化';
    
    controlBtn.addEventListener('click', () => {
      togglePlugin();
    });

    document.body.appendChild(controlBtn);
  }

  // 更新控制按钮
  function updateControlButton() {
    const btn = document.getElementById('xxljob-control-btn');
    if (btn) {
      updateControlButtonText(btn);
    }
  }

  function updateControlButtonText(btn) {
    if (isEnabled) {
      btn.innerHTML = '📖';
      btn.title = '点击关闭目录优化';
      btn.classList.add('enabled');
    } else {
      btn.innerHTML = '📕';
      btn.title = '点击开启目录优化';
      btn.classList.remove('enabled');
    }
  }

  // 页面加载完成后执行
  
  // 总是等待 DOM 完全加载后再初始化
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initOptimization);
  } else {
    initOptimization();
  }
})();

